package com.itheima.reggie.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

// 所有使用到 @RestController注解 和 @Controller注解 抛出的异常都会被监视
// @ControllerAdvice(annotations = {RestController.class, Controller.class})
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 以下方法专门用于捕获 SQLIntegrityConstraintViolationException 异常
     * @return 返回一个出错的 R 实例对象
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        if (exception.getMessage().contains("Duplicate entry")) {
            String[] split = exception.getMessage().split(" ");
            String msg = split[2] + " 已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 捕获 CustomException 异常的方法
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception) {
        return R.error(exception.getMessage());
    }
}
